package com.rzico.core.controller;

import com.alibaba.fastjson.JSONObject;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.core.entity.*;
import com.rzico.core.service.*;
import com.rzico.jwt.JwtTokenUtil;
import com.rzico.util.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.*;

/**
 *  商户接口
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2019-12-02
 */
@Api(description = "商户接口")
@RestController
@Slf4j
@RequestMapping("/mch")
public class MchController extends BaseController {


    @Autowired
    private SysMchService sysMchService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisHandler redisHandler;

    @Value("${jwt.tokenSecret}")
    private String tokenSecret;

    @Value("${jwt.tokenPrefix}")
    private String tokenPrefix;

    @Autowired
    public JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;


    /**
     * 获取当前账号商户资料
     *
     * @return
     */
    @ApiOperation("获取当前账号商户资料")
    @GetMapping("/getInfo/{mchId}")
    public CommResult<SysMch> getInfo(@ApiParam(name="mchId",value="商户号mchId",required=true)@PathVariable String mchId) {
        SysMch sysMch = sysMchService.findById(mchId);
        return CommResult.success(sysMch);
    }


    /**
     * 注册商户
     *
     * @param username
     * @return
     */
    @ApiOperation("注册商户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名（手机/邮箱）,子账号加前缀(mch_商户号_)", required=true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "verifyCode", value = "验证码", required=true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "登录密码（MD5）", required=false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "mchName", value = "商户名", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "scopeType", value = "商户类型", dataType = "Integer", paramType = "query")
    })
    @PostMapping("/register")
    public CommResult<SysUser> register(String username,String mchName,String verifyCode,String password,Integer scopeType,HttpServletRequest request) {
        Assert.notNull(username, "用户名不能为空");
        Assert.notNull(verifyCode, "验证码不能为空");
        int result = sysUserService.checkUserExists(username);
        if (result > 0) {
            return CommResult.error("用户名已存在");
        }
        Integer userType = 1;
        String originalUsername = username;
        String key = Keys.format(RedisHandler.CORE_MODULE_YZM_KEY, originalUsername);
        String code = (String) redisHandler.get(key);
        if (StringUtils.isEmpty(code)){
            return CommResult.error("验证码已过期");
        }
        if (!verifyCode.equals(code)){
            return CommResult.error("验证码错误");
        }
        redisHandler.remove(key);

        SysUser sysUser = new SysUser();
        sysUser.setCreateDate(new Date());
        sysUser.setUsername(username);
        if (originalUsername.indexOf("@")>=0) {
            sysUser.setNickname("邮箱用户"+originalUsername.substring(0,5));
        } else {
            sysUser.setNickname("手机用户"+originalUsername.substring(username.length()-3));
        }
        sysUser.setDelFlag(false);
        sysUser.setStatus(SysUser.STATUS_ENABLED);
        sysUser.setUserType(userType);
        sysUser.setId(CodeGenerator.getUUID());
        if (password==null) {
            password = MD5Utils.getMD5Str(username);
        }
        sysUser.setPassword(MD5Utils.getMD5Str(password.trim() + sysUser.getUsername().trim()));

        int affectCount = sysMchService.register(sysUser,mchName,scopeType);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        final String jwToken = tokenPrefix + jwtTokenUtil.generateToken(userDetails);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", jwToken);
        jsonObject.put("userInfo", sysUser);
        jsonObject.put("mchId",sysUser.getMchId());
        return CommResult.success(jsonObject);
    }



}
